//
//  LGFShowImagesView.swift
//  MedicalUnion
//
//  Created by apple on 2019/8/26.
//  Copyright © 2019 William_Xue. All rights reserved.
//

import UIKit

class LGFShowImagesView: UIView {
    
    var imagesCV: UICollectionView!// 图片 collectionView
    var indexLabel: UILabel!
    var selectIndex: Int!// 选中 index
    var imageArr: [UIImage]!// 图片数组
    
    class func lgf(imageArr: [UIImage],
                   selectIndex: Int,
                   isShowDelete: Bool) -> Void {
        if imageArr.count == 0 {
            return
        }
        let view: LGFShowImagesView = LGFShowImagesView.init()
        let SV = UIApplication.shared.keyWindow!
        view.frame = SV.bounds
        SV.addSubview(view)
        view.imageArr = imageArr
        view.selectIndex = selectIndex
        view.backgroundColor = UIColor.black.withAlphaComponent(0.0)
        view.configView()
        view.imagesCV.transform = CGAffineTransform.init(translationX: 0, y: UIDevice.lgf_ScreenH)
        DispatchQueue.main.async {
            UIView.animate(withDuration: 0.35) {
                view.imagesCV.transform = CGAffineTransform.identity
                view.backgroundColor = UIColor.black.withAlphaComponent(1.0)
            }
        }
    }
    
    func configView() {
        imagesCV = UICollectionView.init(frame: self.bounds, collectionViewLayout: UICollectionViewFlowLayout.lgf_ZeroSpacLayout(.horizontal))
        imagesCV.backgroundColor = UIColor.clear
        imagesCV.isPagingEnabled = true
        imagesCV.lgf_Register(cellType: LGFShowImagesViewCell.self)
        imagesCV.delegate = self
        imagesCV.dataSource = self
        imagesCV.setContentOffset(CGPoint.init(x: UIDevice.lgf_ScreenW * CGFloat(selectIndex - 1), y: 0), animated: false)
        addSubview(imagesCV)
        
        indexLabel = UILabel.init(frame: CGRect.init(x: 0, y: UIDevice.lgf_ScreenH - 45, w: UIDevice.lgf_ScreenW - 20, h: 45))
        indexLabel.textColor = UIColor.white
        indexLabel.textAlignment = .right
        indexLabel.text = selectIndex.description + "/" + imageArr.count.description
        addSubview(indexLabel)
    }
}

extension LGFShowImagesView: UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return UIScreen.main.bounds.size
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArr.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: LGFShowImagesViewCell.self, for: indexPath)
        cell.image = imageArr[indexPath.item]
        cell.delegate = self
        return cell
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        indexLabel.text = (scrollView.lgf_HorizontalIndex() + 1).description + "/" + imageArr.count.description
    }
}

extension LGFShowImagesView: LGFShowImagesViewCellDelegate {
    func showImagesViewTap(_ cell: LGFShowImagesViewCell) {
        UIView.animate(withDuration: 0.35, animations: {
            self.imagesCV.transform = CGAffineTransform.init(translationX: 0, y: UIDevice.lgf_ScreenH)
            self.backgroundColor = UIColor.black.withAlphaComponent(0.0)
        }) { (finish) in
            self.removeFromSuperview()
        }
    }
}

/// LGFShowImagesViewCell
protocol LGFShowImagesViewCellDelegate: class {
    func showImagesViewTap(_ cell: LGFShowImagesViewCell) -> Void
}

class LGFShowImagesViewCell: UICollectionViewCell {
    
    weak var delegate: LGFShowImagesViewCellDelegate?
    
    var imageVBack: UIScrollView!
    var imageV: UIImageView!
    var scrollOffset: CGPoint!
    var image: UIImage! {
        didSet {
            if imageV != nil && image != nil {
                let ratio = self.lgf_Width / image.size.width
                imageV.image = image
                imageV.lgf_Size = CGSize.init(width: self.lgf_Width, height: image.size.height * ratio)
                var maxScale = self.lgf_Height / imageV.lgf_Height
                maxScale = self.lgf_Width / imageV.lgf_Width > maxScale ? self.lgf_Width / imageV.lgf_Width : maxScale
                imageVBack.maximumZoomScale = (maxScale > imageVBack.minimumZoomScale ? maxScale : imageVBack.minimumZoomScale) * 2
                imageV.center = centerOfScrollViewContent(imageVBack)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
        imageVBack = UIScrollView.init(frame: UIScreen.main.bounds)
        imageVBack.minimumZoomScale = 1.0
        imageVBack.delegate = self
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tap(_:)))
        imageVBack.addGestureRecognizer(tap)
        let doubletap = UITapGestureRecognizer.init(target: self, action: #selector(doubleTap(_:)))
        doubletap.numberOfTapsRequired = 2
        imageVBack.addGestureRecognizer(doubletap)
        tap.require(toFail: doubletap)
        addSubview(imageVBack)
        
        imageV = UIImageView.init()
        imageVBack.addSubview(imageV)
    }
    
    @objc func doubleTap(_ sender: UIButton) {
        if self.imageVBack.zoomScale == imageVBack.maximumZoomScale {
            imageVBack.setZoomScale(imageVBack.minimumZoomScale, animated: true)
        } else {
            imageVBack.setZoomScale(imageVBack.maximumZoomScale, animated: true)
        }
    }
    
    @objc func tap(_ sender: UIButton) {
        if self.imageVBack.zoomScale == imageVBack.maximumZoomScale {
            imageVBack.setZoomScale(imageVBack.minimumZoomScale, animated: true)
        } else {
            self.delegate?.showImagesViewTap(self)
        }
    }
    
    func centerOfScrollViewContent(_ scrollView: UIScrollView) -> CGPoint {
        let offsetX = scrollView.lgf_Width > scrollView.contentSize.width ? (scrollView.lgf_Width - scrollView.contentSize.width) * 0.5 : 0
        let offsetY = scrollView.lgf_Height > scrollView.contentSize.height ? (scrollView.lgf_Height - scrollView.contentSize.height) * 0.5 : 0
        let centerX = scrollView.contentSize.width * 0.5 + offsetX
        let centerY = scrollView.contentSize.height * 0.5 + offsetY
        return CGPoint.init(x: centerX, y: centerY)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension LGFShowImagesViewCell: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageV
    }
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        imageV.center = centerOfScrollViewContent(scrollView)
    }
}

extension LGFShowImagesViewCell: UIGestureRecognizerDelegate{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) ->   Bool {
        return true
    }
}


